package com.sluggard.security.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sluggard.security.manage.mapper.CodingMapper;
import com.sluggard.security.manage.model.entity.CodeEntity;
import com.sluggard.security.manage.service.ICodingService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 系统码表 服务实现类
 * </p>
 *
 * @author lizheng
 * @since 2024-04-28
 */
@Service
public class CodingServiceImpl extends ServiceImpl<CodingMapper, CodeEntity> implements ICodingService {

    @Override
    public List<CodeEntity> onList(QueryWrapper<CodeEntity> queryWrapper) {
        List<CodeEntity> codingEntities = baseMapper.selectCustomList(queryWrapper);
        if(CollectionUtils.isEmpty(codingEntities)){
            return codingEntities;
        }
        List<CodeEntity> rootList = codingEntities.stream()
                .filter(item -> item.getPid() == null || item.getPid() == 0L)
                .collect(Collectors.toList());
        buildTree(rootList, codingEntities);
        return rootList;
    }

    @Override
    public List<CodeEntity> listByParentCode(String code) {
        CodeEntity codeEntity = baseMapper.selectByCode(code);
        if(codeEntity == null){
            return null;
        }
        return baseMapper.selectByParentId(codeEntity.getId());
    }

    private void buildTree(List<CodeEntity> rootList, List<CodeEntity> codingEntities) {
        if(CollectionUtils.isEmpty(rootList)){
            return;
        }
        // 递归构建树形结构
        for (CodeEntity root : rootList) {
            List<CodeEntity> children = codingEntities.stream()
                    .filter(item -> item.getPid() != null && item.getPid().equals(root.getId()))
                    .collect(Collectors.toList());
            if(!CollectionUtils.isEmpty(children)){
                root.setChildren(children);
                buildTree(children, codingEntities);
            }
        }
    }
}
